#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
FTPFileName='/opt/coopgis/fromgps/anonymousftproot_OtherReadOnly/incomingftpallpermissions/Locations.csv'
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
import djangoproject
from djangoproject.models import *
#********************Setup psycopg2 and django section********************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update, COOPGIS_FormMisc
from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings



def BuildPoleTreatmentForm(DefaultMap):
    NumberOfPoleTreatmentsListedOnForm=9
    Dict={}
    #Build Map Choices List
    MapChoices=[]
    MapChoices.append([DefaultMap.id, str(DefaultMap.Name)[:30]])
    Maps=Map.objects.all()
    for i in Maps:
        if(not i == DefaultMap):
            MapChoices.append([i.id, str(i.Name)[:30]])
    #Create the PoleTreatmentTypeChoices
    PoleTreatmentTypeChoices=[]
    PoleTreatmentTypes=PoleTreatmentType.objects.all().order_by('Name')
    PoleTreatmentTypeChoices.append(['-1', 'None'])
    for i in PoleTreatmentTypes:
        PoleTreatmentTypeChoices.append([i.id, str(i)])
    #Create the PoleTreatmentCompanyChoices
    PoleTreatmentCompanyChoices=[]
    PoleTreatmentCompanies=Company.objects.all().filter(PoleTreatmentIndicator=True).order_by('Name')
    PoleTreatmentCompanyChoices.append(['-1', 'None'])
    for i in PoleTreatmentCompanies:
        PoleTreatmentCompanyChoices.append([i.id, str(i)])
    for poleTreatment in range(0, NumberOfPoleTreatmentsListedOnForm):
        Dict['UpdateIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentid' + str(poleTreatment)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['PoleTreatmentType' + str(poleTreatment)]=forms.ChoiceField(PoleTreatmentTypeChoices, required=False)
        Dict['PoleTreatmentCompany' + str(poleTreatment)]=forms.ChoiceField(PoleTreatmentCompanyChoices, required=False)
        Dict['PoleTreatmentDate' + str(poleTreatment)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7'}))    
        Dict['PoleTreatmentBrokenCrossarmIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentBrokenGuyIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentBrokenInsulatorIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentVisualInspectionIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentVisualInspectionAndExcavationIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentInternalTreatmentIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentInternalVoidTreatmentIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentLightningArrestorBlownIndicator' + str(poleTreatment)]=forms.BooleanField()        
        Dict['PoleTreatmentNewPoleIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentPoleLeaningIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentSplitTopIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentInternalDecayTreatmentIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentWoodpeckerHolesIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentWireNeutralLowIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentWirePrimaryLowIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentWireSecondaryLowIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentRotIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentGroundlineTreatmentIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentRejectedIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentDataRecordOnlyIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentRepairedGroundIndicator' + str(poleTreatment)]=forms.BooleanField()
        Dict['PoleTreatmentGuyMarkerReplacedQuantity' + str(poleTreatment)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'3'}))    
        Dict['PoleTreatmentGuyMarkerTotalQuantity' + str(poleTreatment)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'3'}))    
        Dict['PoleTreatmentDescription' + str(poleTreatment)]=forms.CharField(max_length = 2500, required=False, widget=forms.TextInput(attrs={'size':'10'}))
        Dict['DeleteIndicator' + str(poleTreatment)]=forms.BooleanField()
    Dict['Map']=forms.ChoiceField(MapChoices, required=False)
    Dict['SelectStationTagNumber']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'4'}))
    Dict['SelectStationid']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'4'}))
    Dict['SelectGPSIndicator']=forms.BooleanField()
    return Dict


def BuildPoleTreatmentReportForm():
    NumberOfPoleTreatmentsListedOnForm=8
    Dict={}
    #Create the PoleTreatmentCompanyChoices
    PoleTreatmentCompanyChoices=[]
    PoleTreatmentCompanies=Company.objects.all().filter(PoleTreatmentIndicator=True).order_by('Name')
    PoleTreatmentCompanyChoices.append(['-1', 'None'])
    for i in PoleTreatmentCompanies:
        PoleTreatmentCompanyChoices.append([i.id, str(i)])
    Dict['PoleTreatmentCompany']=forms.ChoiceField(PoleTreatmentCompanyChoices, required=False)
    Dict['PoleTreatmentStartCreateDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7'}))
    Dict['PoleTreatmentEndCreateDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7'}))
    Dict['PoleTreatmentStartTreatmentDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7'}))
    Dict['PoleTreatmentEndTreatmentDate']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7'}))
    Dict['PoleTreatmentDetailedIndicator']=forms.BooleanField()
    Dict['PoleTreatmentProblemReportOnlyIndicator']=forms.BooleanField()
    return Dict



def ProcessPoleTreatment(form, poleTreatmentFormNumber, SelectionStation, UserName, ProcessQuickLine=False):
    try:
        PoleTreatmentid=int(form.data['PoleTreatmentid' + str(poleTreatmentFormNumber)])
        poleTreatment=compatibleunit.PoleTreatment.objects.filter(id=PoleTreatmentid)[0]
    except:
        PoleTreatmentid='New'
    if(ProcessQuickLine):  #Always create a new pole treatment for the quick line
        PoleTreatmentid='New'
    try:
        PoleTreatmentTypeid=int(form.data['PoleTreatmentType' + str(poleTreatmentFormNumber)])
        poleTreatmentType=compatibleunit.PoleTreatmentType.objects.filter(id__exact=PoleTreatmentTypeid)[0]
        PoleTreatmentTypeName=poleTreatmentType.Name
    except:
        poleTreatmentType=None
        PoleTreatmentTypeName=''
    try:
        Companyid=int(form.data['PoleTreatmentCompany' + str(poleTreatmentFormNumber)])
        company=Company.objects.filter(id__exact=Companyid)[0]
        CompanyName=company.Name
    except:
        company=None
        CompanyName=''    
    try:
        PoleTreatmentDate=COOPGIS_String.StringToDate(form.data['PoleTreatmentDate' + str(poleTreatmentFormNumber)])
    except:
        PoleTreatmentDate=None
    try:
        BrokenGuyIndicator=bool(form.data['PoleTreatmentBrokenGuyIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        BrokenGuyIndicator=False
    try:
        BrokenInsulatorIndicator=bool(form.data['PoleTreatmentBrokenInsulatorIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        BrokenInsulatorIndicator=False
    try:
        VisualInspectionIndicator=bool(form.data['PoleTreatmentVisualInspectionIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        VisualInspectionIndicator=False
    try:
        VisualInspectionAndExcavationIndicator=bool(form.data['PoleTreatmentVisualInspectionAndExcavationIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        VisualInspectionAndExcavationIndicator=False
    try:
        InternalTreatmentIndicator=bool(form.data['PoleTreatmentInternalTreatmentIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        InternalTreatmentIndicator=False
    try:
        InternalVoidTreatmentIndicator=bool(form.data['PoleTreatmentInternalVoidTreatmentIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        InternalVoidTreatmentIndicator=False
    try:
        LightningArrestorBlownIndicator=bool(form.data['PoleTreatmentLightningArrestorBlownIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        LightningArrestorBlownIndicator=False
    try:
        NewPoleIndicator=bool(form.data['PoleTreatmentNewPoleIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        NewPoleIndicator=False
    try:
        PoleLeaningIndicator=bool(form.data['PoleTreatmentPoleLeaningIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        PoleLeaningIndicator=False
    try:
        SplitTopIndicator=bool(form.data['PoleTreatmentSplitTopIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        SplitTopIndicator=False
    try:
        TrimTreesIndicator=bool(form.data['PoleTreatmentTrimTreesIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        TrimTreesIndicator=False
    try:
        InternalDecayTreatmentIndicator=bool(form.data['PoleTreatmentInternalDecayTreatmentIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        InternalDecayTreatmentIndicator=False
    try:
        WoodpeckerHolesIndicator=bool(form.data['PoleTreatmentWoodpeckerHolesIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        WoodpeckerHolesIndicator=False
    try:
        WireNeutralLowIndicator=bool(form.data['PoleTreatmentWireNeutralLowIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        WireNeutralLowIndicator=False
    try:
        WirePrimaryLowIndicator=bool(form.data['PoleTreatmentWirePrimaryLowIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        WirePrimaryLowIndicator=False
    try:
        WireSecondaryLowIndicator=bool(form.data['PoleTreatmentWireSecondaryLowIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        WireSecondaryLowIndicator=False
    try:
        GroundlineTreatmentIndicator=bool(form.data['PoleTreatmentGroundlineTreatmentIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        GroundlineTreatmentIndicator=False
    try:
        RejectedIndicator=bool(form.data['PoleTreatmentRejectedIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        RejectedIndicator=False
    try:
        Description=form.data['PoleTreatmentDescription' + str(poleTreatmentFormNumber)]
    except:
        Description=''
    try:
        UpdateIndicator=bool(form.data['UpdateIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        UpdateIndicator=False
    try:
        DeleteIndicator=bool(form.data['DeleteIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        DeleteIndicator=False
    try:
        BrokenCrossarmIndicator=bool(form.data['PoleTreatmentBrokenCrossarmIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        BrokenCrossarmIndicator=False
    try:
        DataRecordOnlyIndicator=bool(form.data['PoleTreatmentDataRecordOnlyIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        DataRecordOnlyIndicator=False
    try:
        RepairedGroundIndicator=bool(form.data['PoleTreatmentRepairedGroundIndicator' + str(poleTreatmentFormNumber)] == 'on')
    except:
        RepairedGroundIndicator=False
    try:
        GuyMarkerReplacedQuantity=int(form.data['PoleTreatmentGuyMarkerReplacedQuantity' + str(poleTreatmentFormNumber)])
    except:
        GuyMarkerReplacedQuantity=None
    try:
        GuyMarkerTotalQuantity=int(form.data['PoleTreatmentGuyMarkerTotalQuantity' + str(poleTreatmentFormNumber)])
    except:
        GuyMarkerTotalQuantity=None
    RotIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PoleTreatmentRotIndicator' + str(poleTreatmentFormNumber))
    if(not SelectionStation):
        pass #Do not attempt any actions if a station is not selected
    elif(UpdateIndicator and poleTreatmentType and company):
        if(PoleTreatmentid == 'New'):  #Create a New PoleTreatment 
            command=Command()
            command=command.Create(Name='CreatePoleTreatmentFull', StartPoint=SelectionStation.Point, CompanyName=CompanyName, PoleTreatmentDate=PoleTreatmentDate,
                                   CommandUserName=UserName, PoleTreatmentTypeName=PoleTreatmentTypeName, 
                                   BrokenGuyIndicator=BrokenGuyIndicator, BrokenInsulatorIndicator=BrokenInsulatorIndicator,
                                   VisualInspectionIndicator=VisualInspectionIndicator, VisualInspectionAndExcavationIndicator=VisualInspectionAndExcavationIndicator, 
                                   InternalTreatmentIndicator=InternalTreatmentIndicator,
                                   InternalVoidTreatmentIndicator=InternalVoidTreatmentIndicator, LightningArrestorBlownIndicator=LightningArrestorBlownIndicator, 
                                   NewPoleIndicator=NewPoleIndicator, PoleLeaningIndicator=PoleLeaningIndicator, SplitTopIndicator=SplitTopIndicator,
                                   InternalDecayTreatmentIndicator=InternalDecayTreatmentIndicator,
                                   WoodpeckerHolesIndicator=WoodpeckerHolesIndicator, WireNeutralLowIndicator=WireNeutralLowIndicator, 
                                   WirePrimaryLowIndicator=WirePrimaryLowIndicator, WireSecondaryLowIndicator=WireSecondaryLowIndicator,
                                   RotIndicator=RotIndicator,
                                   GroundlineTreatmentIndicator=GroundlineTreatmentIndicator, RejectedIndicator=RejectedIndicator,
                                   Description=Description, DataRecordOnlyIndicator=DataRecordOnlyIndicator, GuyMarkerReplacedQuantity=GuyMarkerReplacedQuantity,
                                   GuyMarkerTotalQuantity=GuyMarkerTotalQuantity,RepairedGroundIndicator=RepairedGroundIndicator,
                                   BrokenCrossarmIndicator=BrokenCrossarmIndicator)
            poleTreatment=command.Process()
        elif(PoleTreatmentid):  #PoleTreatment Already Exists, so Edit it
            PoleTreatmentToEdit=PoleTreatment.objects.filter(id=PoleTreatmentid)[0]
            Age=datetime.datetime.now() - PoleTreatmentToEdit.CreateDateTime
            if(Age.days > 185):
                return #Do not allow editing of Pole Treatments older than ~6 months through the form interface
            if(PoleTreatmentToEdit.ResidesOnServerIndicator):
                command=Command()
                command=command.Create(Name='EditPoleTreatmentFull', PoleTreatmentid=PoleTreatmentid, CompanyName=CompanyName, PoleTreatmentDate=PoleTreatmentDate,
                                   CommandUserName=UserName, PoleTreatmentTypeName=PoleTreatmentTypeName,
                                   BrokenGuyIndicator=BrokenGuyIndicator, BrokenInsulatorIndicator=BrokenInsulatorIndicator,
                                   VisualInspectionIndicator=VisualInspectionIndicator, VisualInspectionAndExcavationIndicator=VisualInspectionAndExcavationIndicator, InternalTreatmentIndicator=InternalTreatmentIndicator,
                                   InternalVoidTreatmentIndicator=InternalVoidTreatmentIndicator, LightningArrestorBlownIndicator=LightningArrestorBlownIndicator, 
                                   NewPoleIndicator=NewPoleIndicator, PoleLeaningIndicator=PoleLeaningIndicator, SplitTopIndicator=SplitTopIndicator,
                                   InternalDecayTreatmentIndicator=InternalDecayTreatmentIndicator,
                                   WoodpeckerHolesIndicator=WoodpeckerHolesIndicator, WireNeutralLowIndicator=WireNeutralLowIndicator, 
                                   WirePrimaryLowIndicator=WirePrimaryLowIndicator, WireSecondaryLowIndicator=WireSecondaryLowIndicator,
                                   GroundlineTreatmentIndicator=GroundlineTreatmentIndicator, RejectedIndicator=RejectedIndicator,
                                   Description=Description, DataRecordOnlyIndicator=DataRecordOnlyIndicator, GuyMarkerReplacedQuantity=GuyMarkerReplacedQuantity,
                                   GuyMarkerTotalQuantity=GuyMarkerTotalQuantity,RepairedGroundIndicator=RepairedGroundIndicator,
                                   BrokenCrossarmIndicator=BrokenCrossarmIndicator)
                command.Process()
            else:
                command=Command.objects.filter(id=PoleTreatmentToEdit.CreateCommand.id)[0]
                command.Set('CompanyName', CompanyName)
                command.Set('PoleTreatmentDate', PoleTreatmentDate)
                command.Set('PoleTreatmentTypeName', PoleTreatmentTypeName)
                command.CommandUserName=UserName
                command.Set('BrokenGuyIndicator', BrokenGuyIndicator)
                command.Set('BrokenInsulatorIndicator', BrokenInsulatorIndicator)
                command.Set('VisualInspectionIndicator', VisualInspectionIndicator)
                command.Set('VisualInspectionAndExcavationIndicator', VisualInspectionAndExcavationIndicator)
                command.Set('InternalTreatmentIndicator', InternalTreatmentIndicator)
                command.Set('InternalVoidTreatmentIndicator', InternalVoidTreatmentIndicator)
                command.Set('LightningArrestorBlownIndicator', LightningArrestorBlownIndicator)
                command.Set('NewPoleIndicator', NewPoleIndicator)
                command.Set('PoleLeaningIndicator', PoleLeaningIndicator)
                command.Set('SplitTopIndicator', SplitTopIndicator)
                command.Set('InternalDecayTreatmentIndicator', InternalDecayTreatmentIndicator)
                command.Set('WoodpeckerHolesIndicator', WoodpeckerHolesIndicator)
                command.Set('WireNeutralLowIndicator', WireNeutralLowIndicator)
                command.Set('WirePrimaryLowIndicator', WirePrimaryLowIndicator)
                command.Set('WireSecondaryLowIndicator', WireSecondaryLowIndicator)
                command.Set('GroundlineTreatmentIndicator', GroundlineTreatmentIndicator)
                command.Set('RejectedIndicator', RejectedIndicator)
                command.Set('Description', Description)
                command.Set('DataRecordOnlyIndicator', DataRecordOnlyIndicator)
                command.Set('GuyMarkerReplacedQuantity', GuyMarkerReplacedQuantity)
                command.Set('GuyMarkerTotalQuantity', GuyMarkerTotalQuantity)
                command.Set('RepairedGroundIndicator', RepairedGroundIndicator)
                command.Set('BrokenCrossarmIndicator', BrokenCrossarmIndicator)
                command.save()
                PoleTreatmentToEdit.Company=company
                PoleTreatmentToEdit.PoleTreatmentDate=PoleTreatmentDate
                PoleTreatmentToEdit.PoleTreatmentType=poleTreatmentType
                PoleTreatmentToEdit.CommandUserName=UserName
                PoleTreatmentToEdit.BrokenGuyIndicator=BrokenGuyIndicator
                PoleTreatmentToEdit.BrokenInsulatorIndicator=BrokenInsulatorIndicator
                PoleTreatmentToEdit.VisualInspectionIndicator=VisualInspectionIndicator
                PoleTreatmentToEdit.VisualInspectionAndExcavationIndicator=VisualInspectionAndExcavationIndicator
                PoleTreatmentToEdit.InternalTreatmentIndicator=InternalTreatmentIndicator
                PoleTreatmentToEdit.InternalVoidTreatmentIndicator=InternalVoidTreatmentIndicator
                PoleTreatmentToEdit.LightningArrestorBlownIndicator=LightningArrestorBlownIndicator
                PoleTreatmentToEdit.NewPoleIndicator=NewPoleIndicator
                PoleTreatmentToEdit.PoleLeaningIndicator=PoleLeaningIndicator
                PoleTreatmentToEdit.SplitTopIndicator=SplitTopIndicator
                PoleTreatmentToEdit.InternalDecayTreatmentIndicator=InternalDecayTreatmentIndicator
                PoleTreatmentToEdit.WoodpeckerHolesIndicator=WoodpeckerHolesIndicator
                PoleTreatmentToEdit.WireNeutralLowIndicator=WireNeutralLowIndicator
                PoleTreatmentToEdit.WirePrimaryLowIndicator=WirePrimaryLowIndicator
                PoleTreatmentToEdit.WireSecondaryLowIndicator=WireSecondaryLowIndicator
                PoleTreatmentToEdit.GroundlineTreatmentIndicator=GroundlineTreatmentIndicator
                PoleTreatmentToEdit.RejectedIndicator=RejectedIndicator
                PoleTreatmentToEdit.Description=Description
                PoleTreatmentToEdit.DataRecordOnlyIndicator=DataRecordOnlyIndicator
                PoleTreatmentToEdit.GuyMarkerReplacedQuantity=GuyMarkerReplacedQuantity
                PoleTreatmentToEdit.GuyMarkerTotalQuantity=GuyMarkerTotalQuantity
                PoleTreatmentToEdit.BrokenCrossarmIndicator=BrokenCrossarmIndicator
                PoleTreatmentToEdit.save()
                PoleTreatmentToEdit.Pole.Station.RebuildSymbology()
    elif(DeleteIndicator and not PoleTreatmentid == 'New'):  #Delete an Existing Assembly, cannot delete a new one
        DeletePoleTreatment(PoleTreatmentid, UserName)

def DeletePoleTreatment(PoleTreatmentid, UserName):
    """Returns the id of the command deleted if deleting a command was necessary, otherwise returns 0 if successful"""
    PoleTreatmentToDelete=PoleTreatment.objects.filter(id=PoleTreatmentid)[0]
    if(PoleTreatmentToDelete.ResidesOnServerIndicator):   #Create the appropriate Command if on the server
        command=Command()
        command=command.Create(Name='DeletePoleTreatment', PoleTreatmentid=PoleTreatmentid, CommandUserName=UserName)
        command=command.Process()
        return 0
    else:  #Delete the appropriate commands that would create it on the server if it only exists on the client
        commandid=int(str(PoleTreatmentToDelete.CreateCommand.id)) #int(str()) to force the query to execute before the deletion
        station=PoleTreatmentToDelete.Pole.Station
        PoleTreatmentToDelete.delete()
        command=Command.objects.filter(id__exact=commandid)
        id=command[0].id
        command[0].delete()
        station.RebuildSymbology()
        return id



def ProcessPoleTreatmentReport(form):
    try:
        Companyid=int(form.data['PoleTreatmentCompany'])
        company=Company.objects.filter(id__exact=Companyid)[0]
        CompanyName=company.Name
    except:
        company=None
        CompanyName=''
    try:
        PoleTreatmentStartCreateDate=COOPGIS_String.StringToDate(form.data['PoleTreatmentStartCreateDate'])
    except:
        PoleTreatmentStartCreateDate=None
    try:
        PoleTreatmentEndCreateDate=COOPGIS_String.StringToDate(form.data['PoleTreatmentEndCreateDate'])
    except:
        PoleTreatmentEndCreateDate=None
    try:
        PoleTreatmentStartTreatmentDate=COOPGIS_String.StringToDate(form.data['PoleTreatmentStartTreatmentDate'])
    except:
        PoleTreatmentStartTreatmentDate=None
    try:
        PoleTreatmentEndTreatmentDate=COOPGIS_String.StringToDate(form.data['PoleTreatmentEndTreatmentDate'])
    except:
        PoleTreatmentEndTreatmentDate=None
    try:
        PoleTreatmentDetailedIndicator=bool(form.data['PoleTreatmentDetailedIndicator'] == 'on')
    except:
        PoleTreatmentDetailedIndicator=False
    try:
        PoleTreatmentProblemReportOnlyIndicator=bool(form.data['PoleTreatmentProblemReportOnlyIndicator']=='on')
    except:
        PoleTreatmentProblemReportOnlyIndicator=False

    PoleTreatments=PoleTreatment.objects.all()
    if(company):
        PoleTreatments=PoleTreatments.filter(Company=company)
    if(PoleTreatmentStartCreateDate):
        PoleTreatments=PoleTreatments.exclude(CreateDateTime__lte=PoleTreatmentStartCreateDate)
    if(PoleTreatmentEndCreateDate):
        PoleTreatments=PoleTreatments.exclude(CreateDateTime__gte=PoleTreatmentEndCreateDate)
    if(PoleTreatmentStartTreatmentDate):
        PoleTreatments=PoleTreatments.exclude(PoleTreatmentDate__lte=PoleTreatmentStartTreatmentDate)
    if(PoleTreatmentEndTreatmentDate):
        PoleTreatments=PoleTreatments.exclude(PoleTreatmentDate__gte=PoleTreatmentEndTreatmentDate)
    #Now Generate either the Detailed or Summary Report
    #if(PoleTreatments.count() > 50):  # Testing to keep the report small and fast for debugging
    #    PoleTreatments=PoleTreatments[:50]
    if(PoleTreatmentDetailedIndicator and not PoleTreatmentProblemReportOnlyIndicator):
        Headings=['ID', 'Pole Tag', 'Type', 'Company', 'Date', 'Remarks', 'VisualInspection (P1)', 'Visual Inspection and Excavation (P2)',
                  'GroundlineTreated (P3)', 'Internal Void (P4)', 'Internal Decay Treatment (P5)', 'InternalTreatment (P6)', 'Repaired Ground (P7)', 
                  'Data Record Only (P9)', 'Guy Marker Replaced (P10)', 'Guy Marker Total', 'Rejected (P11)', 
                  'New Pole', 
                  'Broken Crossarm', 'Broken Guy', 'Broken Insulator',  
                  'Lightning Arrestor Blown', 'Pole Leaning', 'Split Top',  
                  'Woodpecker Holes', 'Wire Neutral Low', 'Wire Primary Low', 'Wire Secondary Low' 
                  ]
        Details=[]
        for poleTreatment in PoleTreatments:
            Row=[]
            Row.append(poleTreatment.id)
            Row.append(poleTreatment.Pole.TagNumber)
            Row.append(str(poleTreatment.PoleTreatmentType))
            Row.append(str(poleTreatment.Company))
            Row.append(poleTreatment.PoleTreatmentDate)
            Row.append(poleTreatment.Description)
            Row.append(ConvertBooleanToString(poleTreatment.VisualInspectionIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.VisualInspectionAndExcavationIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.GroundlineTreatmentIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.InternalVoidTreatmentIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.InternalDecayTreatmentIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.InternalTreatmentIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.RepairedGroundIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.DataRecordOnlyIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.GuyMarkerReplacedQuantity))
            Row.append(ConvertBooleanToString(poleTreatment.GuyMarkerTotalQuantity))
            Row.append(ConvertBooleanToString(poleTreatment.RejectedIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.NewPoleIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.BrokenCrossarmIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.BrokenGuyIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.BrokenInsulatorIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.LightningArrestorBlownIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.PoleLeaningIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.SplitTopIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.WoodpeckerHolesIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.WireNeutralLowIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.WirePrimaryLowIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.WireSecondaryLowIndicator))
            Details.append(Row)
    elif(PoleTreatmentProblemReportOnlyIndicator):
        Headings=['Pole Tag', 'Treatment Date', 'Remarks', 'Rejected (P11)', 'Broken Crossarm', 'Broken Guy', 'Broken Insulator', 'Lightning Arrestor Blown',
                  'Pole Leaning', 'Split Top', 'WoodPeckerHoles', 'Wire Neutral Low', 'Wire Primary Low', 'Wire Secondary Low']
        Details=[]
        for poleTreatment in PoleTreatments:
            if(not poleTreatment.Description and not poleTreatment.RejectedIndicator and not poleTreatment.BrokenCrossarmIndicator 
               and not poleTreatment.BrokenGuyIndicator and not poleTreatment.BrokenInsulatorIndicator and not poleTreatment.LightningArrestorBlownIndicator
               and not poleTreatment.PoleLeaningIndicator and not poleTreatment.SplitTopIndicator and not poleTreatment.WoodpeckerHolesIndicator
               and not poleTreatment.WireNeutralLowIndicator and not poleTreatment.WirePrimaryLowIndicator and not poleTreatment.WireSecondaryLowIndicator):
                continue
            Row=[]
            Row.append(poleTreatment.Pole.TagNumber)
            Row.append(poleTreatment.PoleTreatmentDate)
            Row.append(poleTreatment.Description)
            Row.append(ConvertBooleanToString(poleTreatment.RejectedIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.BrokenCrossarmIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.BrokenGuyIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.BrokenInsulatorIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.LightningArrestorBlownIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.PoleLeaningIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.SplitTopIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.WoodpeckerHolesIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.WireNeutralLowIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.WirePrimaryLowIndicator))
            Row.append(ConvertBooleanToString(poleTreatment.WireSecondaryLowIndicator))
            Details.append(Row)            
    else:
        Headings=['Total', 'VisualInspection (P1)', 'Visual Inspection and Excavation (P2)', 'Groundline Treated (P3)',
                  'Internal Void (P4)', 'Internal Decay Treatment (P5)', 'Internal Treatment (P6)',
                  'Repaired Ground (P7)',  'Data Record Only (P9)', 'Guy Marker Replaced (P10)', 'Guy Marker Total',
                  'Rejected (P11)', 'New Pole', 
                  'Broken Crossarm', 'Broken Guy', 'Broken Insulator',  
                  'Lightning Arrestor Blown', 'Pole Leaning', 'Split Top',  
                  'Woodpecker Holes', 'Wire Neutral Low', 'Wire Primary Low', 'Wire Secondary Low']
        Total=PoleTreatments.count()
        DataRecordOnlyTotal=PoleTreatments.filter(DataRecordOnlyIndicator=True).count()
        NewPoleTotal=PoleTreatments.filter(NewPoleIndicator=True).count()
        RejectedTotal=PoleTreatments.filter(RejectedIndicator=True).count()
        RepairedGroundTotal=PoleTreatments.filter(RepairedGroundIndicator=True).count()
        GroundlineTreatedTotal=PoleTreatments.filter(GroundlineTreatmentIndicator=True).count()
        GuyMarkerReplacedQuantityTotal=0
        for poleTreatment in PoleTreatments:
            if(poleTreatment.GuyMarkerReplacedQuantity):  #Do not try to add if a Null Value
                GuyMarkerReplacedQuantityTotal=GuyMarkerReplacedQuantityTotal + poleTreatment.GuyMarkerReplacedQuantity
        GuyMarkerTotalQuantityTotal=0
        for poleTreatment in PoleTreatments:
            if(poleTreatment.GuyMarkerTotalQuantity):  #Do not try to add if a Null Value
                GuyMarkerTotalQuantityTotal=GuyMarkerTotalQuantityTotal + poleTreatment.GuyMarkerTotalQuantity
        BrokenCrossarmTotal=PoleTreatments.filter(BrokenCrossarmIndicator=True).count()
        BrokenGuyTotal=PoleTreatments.filter(BrokenGuyIndicator=True).count()
        BrokenInsulatorTotal=PoleTreatments.filter(BrokenInsulatorIndicator=True).count()
        VisualInspectionTotal=PoleTreatments.filter(VisualInspectionIndicator=True).count()
        VisualInspectionAndExcavationTotal=PoleTreatments.filter(VisualInspectionAndExcavationIndicator=True).count()
        InternalTreatmentTotal=PoleTreatments.filter(InternalTreatmentIndicator=True).count()
        InternalVoidTotal=PoleTreatments.filter(InternalVoidTreatmentIndicator=True).count()
        LightningArrestorBlownTotal=PoleTreatments.filter(LightningArrestorBlownIndicator=True).count()
        PoleLeaningTotal=PoleTreatments.filter(PoleLeaningIndicator=True).count()
        SplitTopTotal=PoleTreatments.filter(SplitTopIndicator=True).count()
        InternalDecayTreatmentTotal=PoleTreatments.filter(InternalDecayTreatmentIndicator=True).count()
        WoodpeckerHolesTotal=PoleTreatments.filter(WoodpeckerHolesIndicator=True).count()
        WireNeutralLowTotal=PoleTreatments.filter(WireNeutralLowIndicator=True).count()
        WirePrimaryLowTotal=PoleTreatments.filter(WirePrimaryLowIndicator=True).count()
        WireSecondaryLowTotal=PoleTreatments.filter(WireSecondaryLowIndicator=True).count()
        Details=[Total, VisualInspectionTotal, VisualInspectionAndExcavationTotal, GroundlineTreatedTotal,
                 InternalVoidTotal, InternalDecayTreatmentTotal, InternalTreatmentTotal, RepairedGroundTotal, DataRecordOnlyTotal, 
                 GuyMarkerReplacedQuantityTotal, GuyMarkerTotalQuantityTotal,  RejectedTotal,               
                 NewPoleTotal, BrokenCrossarmTotal, BrokenGuyTotal,
                 BrokenInsulatorTotal,    
                 LightningArrestorBlownTotal, PoleLeaningTotal, SplitTopTotal, 
                 WoodpeckerHolesTotal, WireNeutralLowTotal, WirePrimaryLowTotal,
                 WireSecondaryLowTotal]
    return Headings, Details, bool(PoleTreatmentDetailedIndicator or PoleTreatmentProblemReportOnlyIndicator)


def PopulatePoleTreatmentFormFields(form, SelectionStation, NumberOfPoleTreatmentsListedOnForm):
    if(SelectionStation):
        PoleTreatments=PoleTreatment.objects.filter(Pole__Station=SelectionStation).order_by('id')
    else:
        PoleTreatments=None
    for poleTreatmentFormNumber in range(0, NumberOfPoleTreatmentsListedOnForm):
        try:
            if(poleTreatmentFormNumber == 0):
                raise(Exception('0 is the QuickLine, populating with a blank form'))
            form.data['UpdateIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentid' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].id
            form.data['PoleTreatmentType' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].PoleTreatmentType.id
            form.data['PoleTreatmentCompany' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].Company.id
            form.data['PoleTreatmentDate' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].PoleTreatmentDate
            form.data['PoleTreatmentBrokenCrossarmIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].BrokenCrossarmIndicator
            form.data['PoleTreatmentBrokenGuyIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].BrokenGuyIndicator
            form.data['PoleTreatmentBrokenInsulatorIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].BrokenInsulatorIndicator
            form.data['PoleTreatmentVisualInspectionIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].VisualInspectionIndicator
            form.data['PoleTreatmentVisualInspectionAndExcavationIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].VisualInspectionAndExcavationIndicator
            form.data['PoleTreatmentInternalTreatmentIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].InternalTreatmentIndicator
            form.data['PoleTreatmentInternalVoidTreatmentIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].InternalVoidTreatmentIndicator
            form.data['PoleTreatmentLightningArrestorBlownIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].LightningArrestorBlownIndicator
            form.data['PoleTreatmentNewPoleIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].NewPoleIndicator
            form.data['PoleTreatmentPoleLeaningIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].PoleLeaningIndicator
            form.data['PoleTreatmentSplitTopIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].SplitTopIndicator
            form.data['PoleTreatmentInternalDecayTreatmentIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].InternalDecayTreatmentIndicator
            form.data['PoleTreatmentWoodpeckerHolesIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].WoodpeckerHolesIndicator
            form.data['PoleTreatmentWireNeutralLowIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].WireNeutralLowIndicator
            form.data['PoleTreatmentWirePrimaryLowIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].WirePrimaryLowIndicator
            form.data['PoleTreatmentWireSecondaryLowIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].WireSecondaryLowIndicator
            form.data['PoleTreatmentRotIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].RotIndicator
            form.data['PoleTreatmentDataRecordOnlyIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].DataRecordOnlyIndicator
            form.data['PoleTreatmentGroundlineTreatmentIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].GroundlineTreatmentIndicator
            form.data['PoleTreatmentRepairedGroundIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].RepairedGroundIndicator
            form.data['PoleTreatmentRejectedIndicator' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].RejectedIndicator
            form.data['PoleTreatmentGuyMarkerReplacedQuantity' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].GuyMarkerReplacedQuantity
            form.data['PoleTreatmentGuyMarkerTotalQuantity' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].GuyMarkerTotalQuantity            
            form.data['PoleTreatmentDescription' + str(poleTreatmentFormNumber)]=PoleTreatments[poleTreatmentFormNumber-1].Description
            form.data['DeleteIndicator' + str(poleTreatmentFormNumber)]=False  
        except:
            form.data['UpdateIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentid' + str(poleTreatmentFormNumber)]=''
            form.data['PoleTreatmentType' + str(poleTreatmentFormNumber)]=-1
            form.data['PoleTreatmentCompany' + str(poleTreatmentFormNumber)]=-1
            form.data['PoleTreatmentDate' + str(poleTreatmentFormNumber)]=''    
            form.data['PoleTreatmentBrokenCrossarmIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentBrokenGuyIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentBrokenInsulatorIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentVisualInspectionIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentVisualInspectionAndExcavationIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentInternalTreatmentIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentInternalVoidTreatmentIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentLightningArrestorBlownIndicator' + str(poleTreatmentFormNumber)]=False        
            form.data['PoleTreatmentNewPoleIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentPoleLeaningIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentSplitTopIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentInternalDecayTreatmentIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentWoodpeckerHolesIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentWireNeutralLowIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentWirePrimaryLowIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentWireSecondaryLowIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentRotIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentDataRecordOnlyIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentGroundlineTreatmentIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentRepairedGroundIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentRejectedIndicator' + str(poleTreatmentFormNumber)]=False
            form.data['PoleTreatmentDescription' + str(poleTreatmentFormNumber)]=''
            form.data['PoleTreatmentGuyMarkerReplacedQuantity' + str(poleTreatmentFormNumber)]=''
            form.data['PoleTreatmentGuyMarkerTotalQuantity' + str(poleTreatmentFormNumber)]=''
            form.data['DeleteIndicator' + str(poleTreatmentFormNumber)]=False



def ConvertBooleanToString(BooleanValue):
    if(BooleanValue):
        return '_*_'
    else:
        return '___'


